package mysqlconn;

import com.alibaba.fastjson.JSON;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.Map;

public class ConfigClient {

    public ConfigClient() {
        init();
    }

    public String driver ="com.mysql.jdbc.driver";//驱动名称
    public String url="jdbc:mysql://192.168.8.105:3306/mydb";//你的mysql数据库表的路径
    public String user ="root";//用户名
    public String password ="******";//密码

    private ZkClient zkClient = new ZkClient("192.168.8.103:2181,192.168.8.104:2181");

    public void init() {
        if (!zkClient.exists("/mysql-connect")) {
            zkClient.createPersistent("/mysql-connect");
        }
        //注册监听器，节点数据改变的类型，接收通知后的处理逻辑定义
        zkClient.subscribeDataChanges("/mysql-connect", new IZkDataListener() {
            public void handleDataChange(String path, Object data) throws Exception {
                //定义接收通知之后的处理逻辑
                System.out.println("数据库配置发生变化，重启本地连接池");
                System.out.println(path + " data is changed ,new data " + data);
                refreshLocalConfig(data);
                MyDataSource.close();
                MyDataSource.init();
            }

            //数据删除--》节点删除
            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path + " is deleted!!");
            }
        });
    }

    public void initConfig() {
        final Object o = zkClient.readData("/mysql-connect" );
        refreshLocalConfig(o);
    }

    private void refreshLocalConfig(Object data){
        Map<String, String> configMap = JSON.parseObject(data.toString(), Map.class);
        if (configMap.containsKey("mysql.driver")) {
            driver = configMap.get("mysql.driver");
        }
        if (configMap.containsKey("mysql.url")) {
            url = configMap.get("mysql.url");
        }
        if (configMap.containsKey("mysql.user")) {
            user = configMap.get("mysql.user");
        }
        if (configMap.containsKey("mysql.password")) {
            password = configMap.get("mysql.password");
        }
    }





}
